﻿using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Windows.Markup;
using System.Windows.Media;

namespace DenisVuyka.Controls.PropertyGrid
{
  /// <summary>
  /// Provides data required by different UI editors.
  /// </summary>
  public static class EditorDataProvider
  {
    /// <summary>
    /// Represents an {x:Null} value.
    /// </summary>
    public const string NullValueString = "{x:Null}";

    #region Fields
    private static ICollection<NamedColor> _defaultColorNames;
    private static ICollection<XmlLanguage> _defaultLanguages;
    #endregion

    #region Properties
        
    
   
    /// <summary>
    /// Gets the default color names.
    /// </summary>
    /// <value>The default color names.</value>
    public static ICollection<NamedColor> DefaultColorNames
    {
      get 
      {
        if (_defaultColorNames == null)
          _defaultColorNames = GetDefaultColorNames();

        return _defaultColorNames; 
      }
    }

    /// <summary>
    /// Gets the default languages.
    /// </summary>
    /// <value>The default languages.</value>
    public static ICollection<XmlLanguage> DefaultLanguages
    {
      get 
      {
        if (_defaultLanguages == null)
          _defaultLanguages = GetDefaultLanguages();

        return _defaultLanguages; 
      }
    }
    #endregion

    #region Implementation
        
    // http://shevaspace.spaces.live.com/blog/cns!FD9A0F1F8DD06954!435.entry
    private static ICollection<NamedColor> GetDefaultColorNames()
    {
      List<NamedColor> names = new List<NamedColor>();

      NamedColor nc;
      MethodAttributes inclusiveAttributes = MethodAttributes.Static | MethodAttributes.Public;

      foreach (PropertyInfo pi in typeof(Colors).GetProperties())
      {
        if (pi.PropertyType == typeof(Color))
        {
          MethodInfo mi = pi.GetGetMethod();
          if ((mi != null) && ((mi.Attributes & inclusiveAttributes) == inclusiveAttributes))
          {
            nc = new NamedColor(pi.Name, (Color)pi.GetValue(null, null));
            names.Add(nc);
          }
        }
      }

      return names;
    }
    
    private static ICollection<XmlLanguage> GetDefaultLanguages()
    {
      List<XmlLanguage> results = new List<XmlLanguage>();
      foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
      {
        if (string.IsNullOrEmpty(ci.IetfLanguageTag)) continue;
        results.Add(XmlLanguage.GetLanguage(ci.IetfLanguageTag));
      }
      return results;
    }
    #endregion
  }
}
